package com.jz.community.modulemine.ui.activity;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.barlibrary.ImmersionBar;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.utils.NetUtil;
import com.jz.community.modulemine.R;
import com.jz.community.modulemine.R2;
import com.orhanobut.logger.Logger;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = RouterIntentConstant.SHARE_GIFT)
public class ShareGiftActivity extends BaseMvpActivity {

    @BindView(R2.id.share_gift_back)
    ImageView shareGiftBack;
    @BindView(R2.id.share_gift_title)
    TextView shareGiftTitle;
    @BindView(R2.id.share_gift_toolbar)
    Toolbar shareGiftToolbar;
    @BindView(R2.id.share_gift_web)
    WebView shareGiftWeb;
    @BindView(R2.id.share_gift_circle)
    LinearLayout shareGiftCircle;
    @BindView(R2.id.share_gift_friend)
    LinearLayout shareGiftFriend;
    @BindView(R2.id.share_gift_bot_rl)
    RelativeLayout shareGiftBotRl;

    private String url;

    private Bitmap bitmap;

    private boolean canShotImg = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getContentView() {
        return R.layout.module_mine_activity_share_gift;
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }

    @Override
    protected void initView() {
        super.initView();
        ImmersionBar
                .with(this)
                .titleBar(shareGiftToolbar)
                .statusBarDarkFont(true, 0.2f)//当白色背景状态栏遇到不能改变状态栏字体为深色的设备时，解决方案
                .init();

        shareGiftTitle.setText("生成邀请卡");

        url = getIntent().getStringExtra("url");
    }

    @Override
    protected void initDatas() {
        super.initDatas();
        initWebSetting();
    }

    private void initWebSetting() {
        WebSettings webSettings = shareGiftWeb.getSettings();

//        //等页面finish后再发起图片加载(加了这句话，调用WebView的截图会有问题)
//        if (Build.VERSION.SDK_INT >= 19) {
//            webSettings.setLoadsImagesAutomatically(true);
//        } else {
//            webSettings.setLoadsImagesAutomatically(false);
//        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //两者都可以
            webSettings.setMixedContentMode(webSettings.getMixedContentMode());
            //mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }


        // 设置 缓存模式
        if (NetUtil.isNetworkAvailable(getApplicationContext())) {
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        } else {
            webSettings.setCacheMode(
                    WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }

        webSettings.setDefaultTextEncodingName("utf-8");// 编码方式

        webSettings.setJavaScriptEnabled(true);

        // 设置加载进来的页面自适应手机屏幕
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);


        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(true);

        //设置渲染的优先级
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // 支持多窗口
        webSettings.setSupportMultipleWindows(true);
        // 开启 DOM storage API 功能
        webSettings.setDomStorageEnabled(true);
        // 开启 Application Caches 功能
        webSettings.setAppCacheEnabled(true);

//        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        //开启截图功能
        shareGiftWeb.setDrawingCacheEnabled(true);

        shareGiftWeb.setWebViewClient(new shareWebClient());

        shareGiftWeb.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                Logger.e("progress");
                if (newProgress == 100) {
                    //init Bitmap
                    canShotImg = true;
                }

                super.onProgressChanged(view, newProgress);
            }


        });

        shareGiftWeb.requestFocus();

        shareGiftWeb.loadUrl(url);

    }

    private class shareWebClient extends WebViewClient {

        /**
         * 加载过程中 拦截加载的地址url
         *
         * @param webView
         * @param s       被拦截的url
         * @return
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String s) {
            Logger.e("WebView ", "shouldOverrideUrlLoading " + s);
            if (s != null) {
                webView.loadUrl(s);
            }
            return true;
        }

        /**
         * 页面加载过程中，加载资源回调的方法
         *
         * @param webView
         * @param s
         */
        @Override
        public void onLoadResource(WebView webView, String s) {
            super.onLoadResource(webView, s);
        }

        /**
         * 页面开始加载调用的方法
         *
         * @param webView
         * @param s
         * @param bitmap
         */
        @Override
        public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
            super.onPageStarted(webView, s, bitmap);

        }

        /**
         * 页面加载完成回调的方法
         *
         * @param webView
         * @param s
         */
        @Override
        public void onPageFinished(WebView webView, String s) {
            super.onPageFinished(webView, s);
            Logger.e("onPageFinished");
            webView.getSettings().setBlockNetworkImage(false);
        }

        @Override
        public void onScaleChanged(WebView webView, float v, float v1) {
            super.onScaleChanged(webView, v, v1);
            if (shareGiftWeb != null) {
                shareGiftWeb.requestFocus();
                shareGiftWeb.requestFocusFromTouch();
            }
        }

        @Override
        public void onReceivedError(WebView webView, int i, String s, String s1) {
            super.onReceivedError(webView, i, s, s1);
            //出现页面错误的时候，不让webView显示了。同时跳出一个错误Toast
            shareGiftWeb.setVisibility(View.INVISIBLE);
            showNormal("请检查您的网络设置");
        }
    }

    private Bitmap shotWeb() {
        //获取Picture对象
        Picture picture = shareGiftWeb.capturePicture();
        //得到图片的宽和高（没有reflect图片内容）
        int width = picture.getWidth();
        int height = picture.getHeight();
        Bitmap showImage = null;
        if (width > 0 && height > 0) {
            //创建位图
            showImage = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(showImage);
            //绘制(会调用native方法，完成图形绘制)
            picture.draw(canvas);

        }

        return showImage;

    }

    private void shareImg(int type, Bitmap bitmap) {
        //设置缩略图
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, 120, 120, true);
        UMImage thumb = new UMImage(this, thumbBmp);
        UMImage image = new UMImage(mActivity, bitmap);
        image.compressStyle = UMImage.CompressStyle.SCALE;//大小压缩，默认为大小压缩，适合普通很大的图
        image.setThumb(thumb);
        if (type == 0) {
            //分享到微信
            new ShareAction(mActivity)
                    .setPlatform(SHARE_MEDIA.WEIXIN)
                    .withMedia(image)
                    .setCallback(umShareListener)//回调监听器
                    .share();

        } else if (type == 1) {
            //分享到微信
            new ShareAction(mActivity)
                    .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                    .withMedia(image)
                    .setCallback(umShareListener)//回调监听器
                    .share();
        }

    }

    private UMShareListener umShareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            showNormal("分享成功");
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            showNormal("分享失败" + t.getMessage());
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            showNormal("分享取消");
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //bitmap 销毁
        if (null != bitmap && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }

        if (shareGiftWeb != null) {
            shareGiftWeb.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            shareGiftWeb.clearHistory();

            ((ViewGroup) shareGiftWeb.getParent()).removeView(shareGiftWeb);
            shareGiftWeb.destroy();
            shareGiftWeb = null;
        }
    }

    @OnClick(R2.id.share_gift_back)
    public void backClick(View view) {
        finish();
    }

    @OnClick(R2.id.share_gift_friend)
    public void frendClick(View view) {
        //分享到微信
        if (canShotImg) {
            bitmap = shotWeb();
            shareImg(0, bitmap);
        }

    }

    @OnClick(R2.id.share_gift_circle)
    public void circleClick(View view) {
        //分享到朋友圈
        if (canShotImg) {
            bitmap = shotWeb();
            shareImg(1, bitmap);
        }

    }
}
